<?php

namespace Portal\Controller;


use Common\Controller\HomebaseController;

class IndexController extends HomebaseController {

    protected $promotionRegistrationModel;
    protected $storeModel;
    protected $memberModel;
    protected $promotersModel;
    public function _initialize(){
        $this->promotionRegistrationModel = M("promotion_registration");
        $this->storeModel = M("store");
        $this->memberModel = M("member");
        $this->promotersModel = M("promoters");
    }
    public function index(){
        $code = I("get.code");
        $value = I("get.value");
        $this->assign('value',$value);
        $this->assign('code',$code);
        $this->display();
    }

    //判断是否为公司内部人
    public function uindex(){
        $userInfo = $_COOKIE['userInfo'];
        if($userInfo != ''){
            $info = $this->promotersModel->where(array("phone_mob"=>$userInfo))->find();
            if(!$info){
                $this->display();
            }else{
                $this->redirect(U('Portal/Index/statistics',array('user_id'=>$info['user_id'])));
            }
        }else{
            $this->display();
        }
    }

    //统计公司推广情况
    public function statistics(){
        $user_id = $_GET['user_id'];
        $info = $this->promotersModel->where(array("user_id"=>$user_id))->find();
        if(!$info){
            $this->error('工作人员不存在！');
        }

        $where['phone'] = $info['phone_mob'];
        //查看邀请次数
        $count = $this->promotionRegistrationModel
            ->where($where)->order('id desc')->count();
        $promotionRegistrationInfo = $this->promotionRegistrationModel
            ->where($where)->order('id desc')->limit(0,10)->select();

        $time = time();
        $num = 0;
        foreach($promotionRegistrationInfo as $k=>$v){
            $promotionRegistrationInfo[$k]['start_time'] = $v['end_time'] - 60*60*24;
            if($v['end_time'] > $time && $v['status'] == 1){
                $promotionRegistrationInfo[$k]['status_value'] = '未注册';
            }elseif($v['status'] == 2){
                $promotionRegistrationInfo[$k]['status_value'] = '已注册';
            }else{
                $promotionRegistrationInfo[$k]['status_value'] = '已失效';
            }
            if($v['create_time'] == 0){
                $promotionRegistrationInfo[$k]['time_value'] = '无';
            }else{
                $promotionRegistrationInfo[$k]['time_value'] = date('Y-m-d H:i:s',$v['create_time']);
            }
            if($v['status'] == 2){
                $num ++;
            }
        }
        //邀请成功率
        $invited_bibi = (sprintf("%.2f",$num / $count) * 100).'%';
        dump($promotionRegistrationInfo);die;
        $this->display();
    }

    //合同说明页
    public function presentationWidthdraw(){
        $info = D("textarea")->where(array('id'=>1))->find();
        $this->assign('info',$info);
        $this->display();
    }
    //协议
    public function promotion_agreement(){
        $info = D("textarea")->where(array('id'=>1))->find();
        $this->assign('info',$info);
        $this->display();
    }
    //获取提交的数据
    public function addPost(){
        $value = I("post.value");
        $codeValue = I("post.code");
        $registrationID = get_decrypt($value);
        $promotionRegistrationInfo = $this->promotionRegistrationModel->where(array("id"=>$registrationID))->find();
        $code = -1;
        $msg = '查询推广人失败';
        if(!empty($promotionRegistrationInfo)){
            $msg = '此链接已经使用过，不可重复注册！';
            if($promotionRegistrationInfo['status'] == 1){
                $time = time();
                $msg = '此链接已经过期！';
                if($time <= $promotionRegistrationInfo['end_time']){
                    $msg = '验证失败';
                    $codeScrit = md5($promotionRegistrationInfo['phone'].'CMPersonPromote'.$value);
                    if($codeScrit == $codeValue){
                        //走注册流程
                        $postData = array(
                            'user_name' => I("post.user_name"),
                            'phone_mob' => I("post.phone_mob"),
                            'password'  => I("post.password"),
//                            'address'   => I("post.address"),
//                            'user_no'   => I("post.user_no")
                        );
                        $result = $this->dataSubmission($postData,$this->promotersModel->where(array('phone_mob'=>$promotionRegistrationInfo['phone']))->getField("user_id"));
                        $msg = $result['msg'];
                        if($result['code'] == 1){
                            $saveData = array(
                                'status' => 2,
                                'invited_phone' => $postData['phone_mob'],
                                'create_time' => $time,
                                'store_id' => $result['user_id']
                            );
                            $save = $this->promotionRegistrationModel->where(array('id'=>$promotionRegistrationInfo['id']))->save($saveData);
                            $msg = '注册失败：链接404';
                            if($save){
                                $code = 1;
                                $msg = '注册成功';
                            }
                        }
                    }
                }
            }
        }
        $arr['code'] = $code;
        $arr['msg'] = $msg;
        echo json_encode($arr);
        exit();
    }

    //数据提交
    public function dataSubmission($postData,$user_id){
        $arr['code'] = -1;
//        $arr['msg'] = '请填写用户名！';
//        if($postData['user_name']){
            $arr['msg'] = '手机号格式错误！';
            if(check_mobile($postData['phone_mob'])){
//                $arr['msg'] = '请填写地址信息！';
//                if($postData['address']){
//                    if($postData['user_no']){
//                        $regx = '/^[1-9]\d{5}(19|20)\d{2}[01]\d[0123]\d\d{3}[xX\d]$/';
//                        if(!preg_match($regx,$postData['user_no'])){
//                            $arr['msg'] = '身份证信息错误';
//                            return $arr;
//                        }
//                    }
                $time = time();
                    $data_member = array(
                        'user_name'   => $postData['phone_mob'],
                        'real_name	' => $postData['user_name'],
                        'password'    => md5($postData['password']),
                        'phone_mob'   => $postData['phone_mob'],
                        'reg_time'    => $time,
//                        'user_no'   => $postData['user_no'],
                        'is_promoters'=> 1,
                        'first_class' => 2
                    );
                    try{
                        $this->memberModel->startTrans();
                        $info = $this->memberModel->where(array('phone_mob'=>$postData['phone_mob']))->find();
                        if(!$info){
                            $res_member = $this->memberModel->add($data_member);

                            $couponSettingModel = M("coupon_setting");
                            $memberCouponModel = M('member_coupon');
                            $register_coupon =$couponSettingModel->where('setting_id = 4')->find();
                            $arr_coupon = array(
                                'coupon_name' => $register_coupon['name'],
                                'remark' => $register_coupon['remark'],
                                'money' => $register_coupon['money'],
                                'min_money' => $register_coupon['min_money'],
                                'user_id' => $res_member,
                                'start_time' => $time,
                                'end_time' => $time+$register_coupon['expiry_time'],
                                'is_used' => 0,
                            );
                            $add_register_coupon = $memberCouponModel->add($arr_coupon);

                            $saveMember = $this->memberModel->where(array("user_id"=>$res_member))->save(array("second_class"=>$res_member));
                            if(!$res_member){
                                $arr['code'] = -1;
                                $arr['msg'] = '注册失败：添加用户失败！';
                                $this->memberModel->rollback();
                                return $arr;
                            }
                            $token = session_id();
                            //保存到app_token表
                            M('AppToken')->add(array(
                                'user_id' => $res_member,
                                'token' => md5('user_'.$res_member.'_'.'_'.time())
                            ));
                        }else{
                            $save = array(
                                'is_promoters'=> 1,
                                's_id' => 2,
                                's_name' => 'Cloud-Moda',
                                'first_class' => 2,
                                'second_class' => $info['user_id'],
                                'third_class' => 0,
                            );
                            $this->memberModel->where(array("user_id"=>$info['user_id']))->save($save);
                            $res_member = $info['user_id'];
                        }

                        $resMemberInfo = $this->storeModel->field("max(serial_number) as serial_number")->find();
                        $data_store = array(
                            'store_id' => $res_member,
                            'store_name' => $postData['phone_mob'],
                            'region_id' => 0,
//                            'address' => $postData['address'],
//                            'region_name' => $postData['address'],
                            'state' => 1,
                            'add_time' => time(),
                            'is_main' => 0,
                            'parent_id' => 2,
                            'is_region_choice' => 1,
                            'serial_number' => $resMemberInfo['serial_number'] + 1,
                            'extension_id'=>$user_id,
                            'store_type' => 'personal'
                        );

                        $res_store = $this->storeModel->add($data_store);
                        if(!$res_store){
                            $arr['code'] = -1;
                            $arr['msg'] = '注册失败：添加店铺失败！';
                            $this->memberModel->rollback();
                            return $arr;
                        }
                        //生成二维码
                        $dataEncrypt = set_encrypt($res_member);
                        $url = SITE_HOST.'/mobile/index.php?app=qrcode&act=download&invite_code=' . $dataEncrypt;
                        $pash = './uploads/qrcode/' . $res_member . '.png';
                        $path = $this->create_png($url, true, $pash, 'H',10,6,false,'',$postData['user_name']);
                        $save = $this->storeModel->where(array('store_id'=>$res_member))->save(array('qr_code'=>$path,'store_logo'=>'data/files/store_2/other/store_logo.png'));
                        $arr['code'] = 1;
                        $arr['msg'] = '注册成功';
                        $arr['user_id'] = $res_member;
                        $this->memberModel->commit();
                    }catch (\Exception $e){

                        return array("code"=>-1,'msg'=>$e->getMessage());
                    }
                }
//            }
//        }
        return $arr;
    }

    /**
     *获取jsapi分享签名
    */
    function getWinChatShareSignature(){
        $pageUrl=$_POST['url'];
        date_default_timezone_set("Asia/Shanghai");
        //获取access_token
        $getTokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".C('WX_WECHAT_APPID')."&secret=".C('WX_WECHAT_APPSECRET');
        $tokenContent = file_get_contents($getTokenUrl);
        $tokenContentObj = json_decode($tokenContent);
        //获取jsapi_ticket
        $getTicketUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$tokenContentObj->access_token."&type=jsapi";
        $ticketContent=file_get_contents($getTicketUrl);
        $ticketContentObj=json_decode($ticketContent);
        $jsapi_ticket=$ticketContentObj->ticket;
        $noncestr=substr(md5(date('Y-m-d H:i:s').time()),0,16);
        $timestamp=time();
        $stringSign="jsapi_ticket=".$jsapi_ticket."&noncestr=".$noncestr."&timestamp=".$timestamp."&url=".$pageUrl."";
        //组装返回结果，供前端使用
        $signature=sha1($stringSign);
        $res['signature']=$signature;
        $res['noncestr']=$noncestr;
        $res['timestamp']=$timestamp;
        echo json_encode($res);


    }





    public function create_png($text, $bool = false, $outfile = false, $level = 'H', $size = 10, $margin = 6, $saveandprint=false,$logopath,$store_name=null)
    {
        require_once '../promotion/simplewind/Core/Library/Vendor/phpqrcode/phpqrcode.php';
        $qrcode = new \QRcode();
        if ( $outfile ) {
            if (!file_exists(dirname($outfile))){
                mkdir(dirname($outfile),0777,true);
            }
            $qrcode::png($text, $outfile, $level, $size, $margin, $saveandprint);
            $QR = file_get_contents($outfile);
        } else {
            ob_start();
            $qrcode::png($text, $outfile, $level, $size, $margin, $saveandprint);
            $QR = ob_get_contents();
            ob_end_clean();
        }

        //判断是否生成带logo的二维码
        if($bool)
        {
            $font = "/data/wwwroot/default/ecmall/promotion/Public/font/msyh.ttc";
            //字体大小
            $size = 15;
            //显示的文字
            $string = $store_name;
            $num1 = $this->abslength($string)/2;
            $x1 = 301-$num1;
            $logo = imagecreate(600,100);
            $black = ImageColorAllocate($logo, 255, 255, 255);
            $black1 = ImageColorAllocate($logo, 0, 0, 0);

            imagefilledrectangle($logo,0,0,600,60,$black);
            $info = imagettftext($logo, $size, 0, $x1, 28, $black1, $font, $string);

            $QR = imagecreatefromstring(file_get_contents($outfile));    //目标图象连接资源。
            $QR_width = imagesx($QR);      //二维码图片宽度
            $QR_height = imagesy($QR);     //二维码图片高度
            $logo_width = imagesx($logo);    //logo图片宽度
            $logo_height = imagesy($logo);   //logo图片高度


            $logo_qr_width = $QR_width;   //组合之后logo的宽度(占二维码的1/5)
            $scale = $logo_width / $logo_qr_width;  //logo的宽度缩放比(本身宽度/组合后的宽度)
            $logo_qr_height = $logo_height / $scale; //组合之后logo的高度
            $from_width = ($QR_width - $logo_qr_width) / 2;  //组合之后logo左上角所在坐标点
            imagecopyresampled($QR, $logo, 0, 600, 0, 0, 580, 100, 600, 100);

            //输出图片
            imagepng($QR, $outfile);
            imagedestroy($QR);
            imagedestroy($logo);
        }
        return $outfile;
    }
    function abslength($s){
        $n = 0;
        preg_match_all("/./us",$s,$matchs);
        foreach($matchs[0] as $p){
            $n += preg_match('#^['.chr(0x1).'-'.chr(0xff).']$#',$p) ? 1 : 2;
        }
        return $n;
    }

}